﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _007_键盘模拟器
{
    public partial class Form1 : Form
    {
        bool IsStop = false;
        bool isStartShutdownTimer = false;
        TimeSpan stopTime;


        public Form1()
        {
            InitializeComponent();
            this.KeyList.SelectedIndex = 0;
            this.SleepTime.Text = "2";
            this.ShutDownTextList.SelectedIndex = 1;
        }

        private void Start_Click(object sender, EventArgs e)
        {
            if (!(e is MouseEventArgs)) return;
            string word = $"{this.KeyList.Text}";
            int waitTime = 1000;
            if (double.TryParse(this.SleepTime.Text, out double result))
            {
                waitTime = int.TryParse((result * 1000).ToString(), out int res) ? res : 1000;
            }
            IsStop = false;
            this.appStatus.Text = "Running";
            this.appStatus.BackColor = System.Drawing.Color.Red;
            this.appStatus.ForeColor = System.Drawing.Color.Black;
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    if (IsStop)
                    {
                        break;
                    }
                    Method(word, waitTime);
                }
            });
        }

        private void Stop_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 10; i++)
            {
                this.IsStop = true;
                Thread.Sleep(100);
            }
            this.appStatus.Text = "Stop";
            this.appStatus.BackColor = System.Drawing.Color.Orange;
            this.appStatus.ForeColor = System.Drawing.Color.Red;
        }

        #region 委托及其事件
        public delegate void SetKeyWord(string word, int waitTime);
        public SetKeyWord Method = new SetKeyWord(SetKey);

        public static void SetKey(string word, int waitTime)
        {
            Thread.Sleep(waitTime);
            SendKeys.SendWait("{" + word + "}");
        }
        #endregion

        private void KeyList_TextChanged(object sender, EventArgs e)
        {
            ComboBox temp = sender as ComboBox;
            if (temp.Text.Length > 1)
            {
                if (char.IsLetter(temp.Text[1]))
                {
                    temp.Text = char.ToUpper(temp.Text[1]).ToString();
                }
                else
                {
                    temp.Text = "A";
                }
            }
            temp.Select(1, 0);
        }

        private void SleepTime_TextChanged(object sender, EventArgs e)
        {
            TextBox temp = sender as TextBox;
            if (!double.TryParse(temp.Text, out double result))
            {
                temp.Text = "1";
            }
            temp.Select(1, 0);
        }

        /// <summary>
        /// 定时关机
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShutdownTimerBtn_Click(object sender, EventArgs e)
        {
            if (isStartShutdownTimer)
            {
                RunCmd("shutdown -a");
                this.ShutdownTimerBtn.Text = "定时关机";
                isStartShutdownTimer = false;
                this.timer1.Enabled = false;
                return;
            }
            var min = Int32.TryParse(this.ShutDownTextList.Text, out int result) ? result : 45;
            RunCmd($"shutdown -s -f -t {min * 60}");
            this.stopTime = DateTime.Now.AddMinutes(min) - DateTime.Now;
            isStartShutdownTimer = true;
            this.timer1.Enabled = true;
        }

        /// <summary>
        /// 关闭进程(雷电模拟器、和本身)
        /// </summary>
        /// <param name="processName">进程名</param>
        private void KillProcess()
        {
            Process[] myproc = Process.GetProcesses();
            //雷电模拟器、当前程序本身
            List<string> exeLs = new List<string> { "dnplayer", "007_键盘模拟器" };
            Dictionary<string, Process> exeDic = new Dictionary<string, Process>();
            foreach (Process item in myproc)
            {
                if (exeLs.Contains(item.ProcessName))
                {
                    exeDic.Add(item.ProcessName, item);
                }
            }
            exeLs.ForEach(x =>
            {
                if (exeDic.TryGetValue(x, out Process process))
                    process.Kill();
            });
        }

        /// <summary>
        /// 操作电脑命令
        /// </summary>
        /// <param name="command"></param>
        private void RunCmd(string command)
        {
            var startInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardInput = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            startInfo.CreateNoWindow = true;
            var myProcess = new System.Diagnostics.Process();
            myProcess.StartInfo = startInfo;
            myProcess.Start();
            myProcess.StandardInput.WriteLine(command);
        }

        /// <summary>
        /// 定时执行程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            stopTime = stopTime.Subtract(new TimeSpan(0, 0, 1));
            this.ShutdownTimerBtn.Text = $"关机倒计时：{stopTime:hh\\:mm\\:ss}";
            //最后半分钟执行关闭程序
            if (stopTime.Ticks / Math.Pow(10, 7) < 30)
            {
                KillProcess();
            }
        }
    }
}
